import type { ProColumns } from '@ant-design/pro-components';
import { ModalForm, ProForm, ProFormDatePicker, ProFormSelect, ProFormText, ProFormTextArea, ProFormTimePicker } from '@ant-design/pro-components';
import type { Meeting } from '@fill/client';
import { client, queryClient } from '@fill/client';
import { Col, Modal, Row, Tabs } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { NODE_TYPE } from '../../constants/default';
import { STATUS_OPTIONS } from '../../constants/select';
import type { IUploadFile } from '../../util';
import { checkStateUpdate } from '../../util/state';
import { Records } from '../rectification/Records';
import { UploadFile } from '../report/Upload';
import { MeetingUpdate } from './Update';

export const meetingTypes: {
  [key: string | number]: {
    text: string
  }
} = {
  1: {
    text: '民主生活会',
  },
  2: {
    text: '党委会议',
  },
};

export const approvalTexts: string[] = ['', '待审批', '审批通过', '审批未通过', '进一步整改待审批', '进一步整改审批通过', '进一步整改审批未通过'];

interface IApprovalTypes {
  [key: string]: string
}
export const approvalTypes: IApprovalTypes = {};
approvalTexts.map((text, index) => approvalTypes[index] = text);

const Detail = (records: Meeting) => {
  const [attachment, setAttachment] = useState<IUploadFile[]>([]);

  useEffect(() => {
    setAttachment(JSON.parse(records?.attachment || '[]'));
  }, [records]);

  return (
    <Row>
      <Col span={24}>
        <ProFormText
          name="slug"
          label="会议主题"
          placeholder="请输入会议主题"
          colProps={{
            md: 24,
          }}
          rules={[
            {
              required: true,
              message: '请输入会议主题',
            },
          ]}
        />
      </Col>
      <Col span={12}>
        <ProFormDatePicker
          name="started_at"
          label="会议日期"
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 8,
          }}
          width="md"
          rules={[
            {
              required: true,
              message: '请选择会议日期',
            },
          ]}
        />

      </Col>
      <Col span={12}>
        <ProFormTimePicker.RangePicker
          name="time"
          label="会议时间"
          dataFormat="HH:mm"
          fieldProps={{
            format: 'HH:mm',
          }}
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 6,
          }}
          width="md"
          rules={[
            {
              required: true,
              message: '请选择会议时间',
            },
          ]}
        />
      </Col>
      <Col span={12}>
        <ProFormText
          name="presenter"
          label="主持人"
          placeholder="请输入主持人"
          rules={[
            {
              required: true,
              message: '请输入主持人',
            },
          ]}
          width="md"
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 8,
          }}
        />
      </Col>
      <Col span={12}>
        <ProFormSelect
          name="types"
          label="会议类型"
          rules={[
            {
              required: true,
              message: '请选择会议类型',
            },
          ]}
          valueEnum={{
            1: {
              text: '民主生活会',
            },
            2: {
              text: '党委会议',
            },
          }}
          width="md"
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 6,
          }}
        />
      </Col>
      <Col span={24}>
        <ProFormSelect label="参会人" rules={[
          {
            required: true,
            message: '请输入参会人',
          },
        ]} name="members" fieldProps={{
          mode: 'tags',
        }} />
      </Col>
      <Col span={24}>
        <ProFormTextArea label="会议提纲" name="outline" />
      </Col>
      <Col span={24}>
        <ProForm.Item style={{
          width: '100%',
        }} labelCol={{
          span: 4,
        }} name="attachment" label="会议材料">
          <UploadFile files={attachment} readonly onChange={() => { }} />
        </ProForm.Item>
      </Col>
    </Row>
  );
};

export const useMeetingDetail = () => {
  const [delOpen, setDelOpen] = useState(false);
  const [current, setCurrent] = useState<Meeting>();
  async function confirmDelete(record: Meeting) {
    setDelOpen(true);
    setCurrent(record);
  }

  async function handleDelete() {
    await queryClient.fetchQuery({
      queryKey: ['meeting.delete'],
      queryFn: () => client.mutation(['meetings.delete', {
        arg: {
          uuid: current?.uuid as string,
        },
      }]),
    });

    queryClient.refetchQueries({
      queryKey: ['meetings.get'],
    });

    setDelOpen(false);
  }

  const MeetingDetail = (records: Meeting) => {
    return (
      <>
        <Modal
          title="提示"
          open={delOpen}
          onOk={() => handleDelete()}
          onCancel={() => setDelOpen(false)}
          okText="确认"
          cancelText="取消"
          mask={false}
          maskStyle={{
          }}
        >
          <p>确认删除?</p>
        </Modal>
        <ModalForm<Meeting>
          width={1000}
          title="会议纪要"
          trigger={
            <a key="link">查看</a>
          }
          layout="horizontal"
          modalProps={{
            destroyOnClose: true,
            onCancel: () => console.log('run'),
          }}
          labelCol={{ span: 4 }}
          rowProps={{
            gutter: [6, 6],
          }}
          initialValues={{
            ...records,
            members: records.members.split(','),
            time: records.time.split(','),
            outline: records.outline?.replaceAll('<br />', '\n'),
          }}
          readonly
          submitter={{
            render(props, dom) {
              return <div style={{
                display: 'flex',
                flex: 1,
                justifyContent: 'center',
              }}>
                {dom[0]}
              </div>;
            },
          }}
        >
          <Tabs defaultActiveKey="1" items={[
            {
              key: '1',
              label: '会议信息',
              children: <Detail {...records} />,
            },
            {
              key: '2',
              label: '提交审批记录',
              children: <Records module={NODE_TYPE.MEETING} relation_uuid={records.uuid} />,
            },
          ]} />
        </ModalForm>
      </>

    );
  };

  const columns: ProColumns<Meeting>[] = [
    {
      dataIndex: 'index',
      title: '序号',
      valueType: 'indexBorder',
      width: 48,
      align: 'center',
    },
    {
      title: '会议主题',
      dataIndex: 'slug',
      align: 'center',

    },
    {
      title: '会议类型',
      dataIndex: 'types',
      align: 'center',
      valueEnum: meetingTypes,
    },
    {
      title: '会议日期',
      dataIndex: 'started_at',
      align: 'center',
      search: false,
      render(dom, entity) {
        return dayjs(entity.started_at).format('YYYY-MM-DD');
      },
    },
    {
      title: '会议时间',
      dataIndex: 'time',
      align: 'center',
      render(dom, entity) {
        return entity.time.split(',').join('-');
      },
    },
    {
      title: '主持人',
      dataIndex: 'presenter',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '审批状态',
      dataIndex: 'state',
      align: 'center',
      valueType: 'select',
      valueEnum: approvalTypes,
    },
    {
      title: '处理状态',
      dataIndex: 'status',
      align: 'center',
      search: false,
      valueEnum: STATUS_OPTIONS,
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (_text, record, _, _action) => [
        <MeetingDetail key="meeting-detail" {...record} />,
        checkStateUpdate(record?.state || '') && <MeetingUpdate key="update" {...record} />,
        <a key="delete" onClick={() => confirmDelete(record)}>删除</a>,
      ],
    },
  ];

  return {
    columns,
  };
};
